package com.heima.behavior.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Date;
import com.heima.behavior.dto.BehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Threadlocals.UserThreadLocalUtil;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-04
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {

    @Autowired
    private IApBehaviorEntryService apBehaviorEntryService;

    /**
     * 根据文章ID和设备ID查询是否点赞
     * @param articleId
     * @param entryId
     * @return
     */
    @Override
    public ApLikesBehavior findByArticleIdAndEntryId(Integer articleId, Integer entryId) {
        LambdaQueryWrapper<ApLikesBehavior> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApLikesBehavior::getEntryId, entryId);
        wrapper.eq(ApLikesBehavior::getArticleId, articleId);
        ApLikesBehavior one = this.getOne(wrapper);
        return one;
    }



    @Override
    public ResponseResult like(BehaviorDto dto) {
        User user = UserThreadLocalUtil.get();
        ApBehaviorEntry entry = apBehaviorEntryService.getEntry(user.getUserId(),dto.getEquipmentId());

        //根据文章id查表
        LambdaQueryWrapper<ApLikesBehavior>  queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApLikesBehavior::getArticleId, dto.getArticleId());
        ApLikesBehavior one = this.getOne(queryWrapper);

        ApLikesBehavior likesBehavior = new ApLikesBehavior();


        likesBehavior.setEntryId(entry.getId());
        likesBehavior.setArticleId(dto.getArticleId());
        likesBehavior.setType(0);
        likesBehavior.setOperation(dto.getOperation());
        likesBehavior.setCreatedTime(new Date());
        //如果没有新增,存在则保存
        if(one==null){
            this.save(likesBehavior);
        } else{
            likesBehavior.setId(one.getId());
            this.updateById(likesBehavior);
        }


        return ResponseResult.okResult();


    }
}
